#coding=utf-8
import json,requests,base64,getpass,pymysql
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info
from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement

def webdriver_init():
    chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
    chrome_options.add_argument('--headless')   # 增加无界面选项
    chrome_options.add_argument('log-level=3')
    chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
    chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
    u=webdriver.Chrome(options=chrome_options,executable_path="./chromedriver")
    return u
    
def mysql_init():
    db = pymysql.connect(host='',
                     port=8888,
                     user='root',
                     password='',
                     database='courseaction',
                     cursorclass=pymysql.cursors.DictCursor)
    return db

def login_action(u,un,pw):
    u.find_element_by_id('schoolId').click()
    u.find_element_by_xpath('//select/option[@value="15"]').click()  
    u.find_element_by_id('username').send_keys(un)
    u.find_element_by_id('password').send_keys(pw)
    u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
    try:
        sleep(1)
        u.find_element_by_xpath('//div/a[@class="layui-layer-btn0"]').click()
        cookies = u.get_cookies()
        cookieall=''
        for cookie in cookies:
            cookieall+=cookie['name']+'='+cookie['value']+";"
        download(u.find_element_by_id("codeImg").get_attribute('src'),cookieall[:-1])
        sleep(1)
        result = base64_api(uname='yusheng615', pwd='1731249586', img=Image.open('./code/'+username))
        sleep(1)   
        u.find_element_by_id('code').send_keys(result)
        sleep(0.5)
        u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
    except:
        return "无验证码或没找到验证码"

def getwximage(u):
    sleep(3)
    r = requests.get(u.find_element_by_class_name("qrcode").get_attribute('src'))
    with open('./admin/'+username+'.png', 'wb') as f:
        f.write(r.content)#保存
    return "微信二维码已保存在相应目录"

def download(url, cookie):
    header = {
        "Cookie": cookie,
        }
    r = requests.get(url, headers=header)
    with open('./code/'+username, 'wb') as f:
        f.write(r.content)

def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""

def fakewxcookie():
    global u
    u=webdriver_init()
    u.get('https://mooc.yinghuaonline.com/user/login')
    sleep(1)
    login_action(u,auname,apwd)
    print_log(getwximage(u)+"\n请管理员扫码")
    for _ in range(20):
        sleep(30)
        try:
            u.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[3]/div[1]/a/div[2]')
            break
        except:
            continue
    try:
        print_log("扫描成功管理员为："+u.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[3]/div[1]/a/div[2]').text)
    except:
        print_log("微信扫码失败或未及时扫描")
        quit_c()
    sleep(5)
    u.get('https://mooc.yinghuaonline.com/user')
    sleep(5)
    cookie=u.get_cookies()[2]['value']
    u.quit()
    u=webdriver_init()
    setcookie(cookie,u,'mooc.yinghuaonline.com')
    setcookie(cookie,u,'.yinghuaonline.com')
    login_action(u,username,password)
    sleep(3)
    try:
        u.find_element_by_class_name("layui-layer-btn0").click()
    except:
        sleep(0.1)
    try:
        name=u.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[3]/div[1]/a/div[2]').text
        if cursor.execute('SELECT `uname` FROM `cadata` where uname=%s'%username)==0:
            cursor.execute("insert into cadata(`uname`,`pwd`,`cookie`,`pid`) values('%s','%s','%s','%s')"%(username,password,cookie,pid))
            db.commit()
        else:
            cursor.execute("update `cadata` set cookie='%s' where uname='%s'"%(cookie,username))
        u.quit()
        return "绑定成功\n用户："+name
    except Exception as e:
        print_log("绑定失败\n"+str(e))
        quit_c()

def setcookie(cookie,u,domain):
    token = {'domain': domain,'name': 'token', 'value': cookie}
    u.get('https://mooc.yinghuaonline.com/user/login')
    sleep(3)
    u.add_cookie(token)

def optionCourse(cname):
    course_list = u.find_elements_by_xpath('/html/body/div[3]/div[2]/div[2]/div[1]/div[4]/div/div/div[2]/div[1]/a')
    course_list[int(cname)-1].click()
    sleep(2)
    return "课程选择成功"

def play():
    url = u.find_element_by_link_text("学习成绩").get_attribute('href')
    u.get(url) 
    print_log("已经学习 %s 个视频" % u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]').text)
    print_log("尚未学习 %s 个视频" % u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]').text) 

    while True:
        sleep(1)
        try:
            #未学完
            u.find_element_by_id('state').click()
            u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
            u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
            sleep(1)
            href_list = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
            u.get(href_list[0].get_attribute('href'))
        except:
            try:
                #未学
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(1)
                href_list = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                u.get(href_list[0].get_attribute('href'))
            except:
                break
                
        sleep(2)
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()#静音
        
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]/canvas').click()
        
        for _ in range(3):
            try:
                sleep(10)
                yzm = u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/img[2]').get_attribute('src')
                
                cookies = u.get_cookies()
                cookieall=''
                for cookie in cookies:
                    cookieall+=cookie['name']+'='+cookie['value']+";"

                download(yzm,cookieall[:-1])
                result = base64_api(uname='yusheng615', pwd='1731249586', img=Image.open(username))
                
                sleep(1)
                u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/input[2]').send_keys(result)
                sleep(1)
                u.find_element_by_link_text("开始播放").click()
            except:
                break

        print_log("开始时间是%s" % datetime.now())
        cursor.execute("update `cadata` set `state`='1' where `uname`='%s'"%username)
        db.commit()
        
        try:
            stime='00'
            ttime='00'
            while True:
                sleep(10)
                time=u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]').text
                print_log("播放中："+time)
                
                if ttime==str(time[:2]).strip() and stime==str(time[3:5]).strip():
                    print_log("视频暂停或完结")
                    break

                stime=str(time[3:5]).strip()
                ttime=str(time[:2]).strip()

                sleep(300)#300
        except Exception as e:
            cursor.execute("update `cadata` set `state`='-1' where `uname`='%s'"%username)
            db.commit()
            print_log("异常退出\n"+str(e))
            quit_c()

        u.get(url) 
        print_log("已经学习 %s 个视频" % u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]').text)
        n=u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]').text
        print_log("尚未学习 %s 个视频" % n)
        if n=='0':
            cursor.execute("SELECT `count` FROM `cadata` where uname='%s'"%username)
            count=str(int(cursor.fetchone()['count'])+1)
            cursor.execute("update `cadata` set `state`='2',`count`='%s' where uname='%s'"%(count,username))
            db.commit()

def quit_c():
    cursor.close()
    db.close()
    u.quit()
    exit()

def print_log(string):
    string+='\n'
    with open("./log/"+username+'.log', 'a') as f:
        f.write(string)

def init(un,pd,ID):
    global db
    global cursor
    global username
    global password
    global pid
    db=mysql_init()
    cursor = db.cursor()
    username=un
    password =pd
    pid=ID

def run(un,pd,course,ID):
    init(un,pd,ID)
    global cookie
    global auname
    global apwd
    global u
    
    if cursor.execute('SELECT `cookie` FROM `cadata` where uname=%s'%username)==0:
        if cursor.execute('SELECT `id`,`number` FROM `admin`')==0:
            print_log("请先添加管理员账号。")
            quit_c()

        cursor.execute('SELECT `uname`,`pwd` FROM `admin` where id=%s' % pid)
        admin=cursor.fetchone()
        auname=admin['uname']
        apwd=admin['pwd']
        cookie=''
        print_log(fakewxcookie())
        
    cursor.execute('SELECT `cookie` FROM `cadata` where uname=%s'%username)
    cookie=cursor.fetchone()['cookie']
    u=webdriver_init()
    setcookie(cookie,u,'.yinghuaonline.com')
    u.get('https://mooc.yinghuaonline.com/user')
    sleep(3)
    try:
        u.find_element_by_class_name("layui-layer-btn0").click()
    except:
        sleep(1)
        
    try:
        sleep(2)
        try:
            print_log("登录成功\n用户："+u.find_element_by_xpath('/html/body/div[1]/div/div[2]/div[3]/div[1]/a/div[2]').text)
        except:
            print_log("登录失败")
            quit_c()
            
        print_log(optionCourse(str(course)))
        cursor.execute('SELECT `state` FROM `cadata` where uname=%s'%username)
        if cursor.fetchone()['state']=='1':
            raise Exception("同一时间只能运行一个脚本")
    except Exception as e:
        print_log("出错了\n"+str(e))
        quit_c()

    play()
    quit_c()